package com.ujiuye.dao;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.ujiuye.bean.User;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class Homework01Dao {
    private QueryRunner qr = new QueryRunner(new ComboPooledDataSource());
    /**
     * 账号唯一
     * @param username
     * @return
     */
    public int usernameIsUnique(String username) {
        String sql = "select count(*) from user where username = ?";
        try {
            long l = (long)qr.query(sql,new ScalarHandler(),username);
            return (int)l;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 手机号唯一
     * @param phone
     * @return
     */
    public int phoneIsUnique(String phone) {
        String sql = "select count(*) from user where phone = ?";
        try {
            long l = (long)qr.query(sql,new ScalarHandler(),phone);
            return (int) l;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 模糊搜索
     * @param username
     * @return
     */
    public List<User> dimQuery(String username) {
        //select * from user where username like '张%'
        String sql = "select * from user where username like '" + username + "%'";
        try {
            return qr.query(sql,new BeanListHandler<>(User.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
